package com.czh.framework.security.config;

import com.czh.common.date.RedisCache;
import com.czh.framework.security.authentication.JwtAuthentication;
import com.czh.framework.security.filter.JwtAuthenticationFilter;
import com.czh.framework.security.handler.AuthenticationFaultHandler;
import com.czh.framework.security.handler.AuthorizationFaultHandler;
import com.czh.framework.security.provider.JwtAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Filter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启授权
public class SecurityConfig {

//    @Autowired
//    JwtAuthentationFilter filter;

    public static final String LOGIN_PATH = "/login";
    public static final String LOGIN_OUT = "";


    @Autowired
    AuthenticationFaultHandler authenticationFaultHandler;
    @Autowired
    AuthorizationFaultHandler authorizationFaultHandler;


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public AuthenticationManager authenticationManagerBean(DaoAuthenticationProvider daoAuthenticationProvider,
                                                           JwtAuthenticationProvider jwtAuthenticationProvider) throws Exception {
        List<AuthenticationProvider> list = new ArrayList<>();

        list.add(daoAuthenticationProvider);
        list.add(jwtAuthenticationProvider);

        ProviderManager providerManager = new ProviderManager(list);
        return providerManager;
    }
    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider(UserDetailsService userDetailsService,
                                                               PasswordEncoder passwordEncoder) {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        return daoAuthenticationProvider;
    }
    @Bean
    public JwtAuthenticationProvider jwtAuthenticationProvider(RedisCache redisCache) {
        JwtAuthenticationProvider jwtAuthenticationProvider = new JwtAuthenticationProvider(redisCache);
        return jwtAuthenticationProvider;
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter(RedisCache redisCache,AuthenticationManager authenticationManager) {
        return new JwtAuthenticationFilter(redisCache,authenticationManager);
    }

    @Bean
    protected SecurityFilterChain configure(HttpSecurity http,JwtAuthenticationFilter jwtAuthenticationFilter) throws Exception {
        final DefaultSecurityFilterChain build1 = http
                .csrf().disable()//不需要 因为 token 天生防止 csrf
                .cors().and()//要跨域 因为 会有跨域过滤器 CorsOrigin
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .formLogin().disable()
                .logout().disable()
                .authorizeHttpRequests(author -> {
                    author.antMatchers("/auth/*").permitAll()
                            //此处可添加授权信息
                            .antMatchers("/test").hasAuthority("test")
                            .antMatchers("/test/author").hasAuthority("test2")
                            .anyRequest().authenticated();
                })
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling()
                .authenticationEntryPoint(authenticationFaultHandler)
                .accessDeniedHandler(authorizationFaultHandler).and().build();
        return build1;
    }
}
